﻿using Duende.IdentityModel;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Stores;
using Service.Auth.Api.Application.Query;

namespace Service.Auth.Api.Extensions
{
    public class MysqlResourceStore(ScopeApiResourcesQueryService queryService) : IResourceStore
    {
        public async Task<IEnumerable<ApiResource>> FindApiResourcesByNameAsync(IEnumerable<string> apiResourceNames)
        {
            var apis = await queryService.QueryScopeApiResourcesList();
            var apiResources = apis.Where(s => apiResourceNames.Contains(s.ApiId))
                .Select(item => new ApiResource(item.ApiId, item.Desc, new List<String>() { JwtClaimTypes.Role })
                { Scopes = { item.Id } }).ToList();
            return apiResources;
        }

        public async Task<IEnumerable<ApiResource>> FindApiResourcesByScopeNameAsync(IEnumerable<string> scopeNames)
        {
            var apis = await queryService.QueryScopeApiResourcesList();
            var apiResources = apis.Where(s => scopeNames.Contains(s.Id))
                .Select(item =>
                    new ApiResource(item.ApiId, item.Desc,
                        new List<String>() { JwtClaimTypes.Role })
                    { Scopes = { item.Id } })
                .ToList();
            return apiResources;
        }

        public async Task<IEnumerable<ApiScope>> FindApiScopesByNameAsync(IEnumerable<string> scopeNames)
        {
            var apis = await queryService.QueryScopeApiResourcesList();
            return apis.Where(s => scopeNames.Contains(s.Id)).Select(s => new ApiScope(s.Id)).ToList();
        }

        public async Task<IEnumerable<IdentityResource>> FindIdentityResourcesByScopeNameAsync(
            IEnumerable<string> scopeNames)
        {
            var result = new List<IdentityResource>
            {
                new IdentityResources.OpenId(), //必须要添加，否则报无效的scope错误
                new IdentityResources.Profile()
            };
            return await Task.FromResult(result);
        }

        public async Task<Resources> GetAllResourcesAsync()
        {
            var apis = await queryService.QueryScopeApiResourcesList();
            var apiResources = apis.Select(item =>
                new ApiResource(item.ApiId, item.Desc, new List<String>() { JwtClaimTypes.Role })
                { Scopes = { item.Id } }).ToList();
            var result = new Resources(new List<IdentityResource>
            {
                new IdentityResources.OpenId(), //必须要添加，否则报无效的scope错误
                new IdentityResources.Profile()
            }, apiResources, apis.Select(s => new ApiScope(s.Id)).ToList());
            return result;
        }
    }
}